import axios, { AxiosError } from 'axios';
import { message } from 'antd';
import { readAuth } from '../utils/storage';

const http = axios.create({
  baseURL: '/api',
  timeout: 10000,
});

// 请求拦截(token)
http.interceptors.request.use(config => {
  const token = readAuth()?.token;
  if (token && config.headers) config.headers['Authorization'] = 'Bearer ' + token;
  return config;
});

// 响应拦截 & 统一错误处理
http.interceptors.response.use(res => {
  // 业务错误码处理可在此加
  return res.data;
}, (error: AxiosError) => {
  let msg = '网络错误';
  if (error.response) {
    const code = (error.response as any).status;
    if (code === 401) msg = '未登录或登录已过期';
    else if (code === 403) msg = '没有权限';
    else if (code === 500) msg = '服务器异常';
    else if ((error.response.data as any)?.message) msg = (error.response.data as any).message;
  } else if (error.message) {
    msg = error.message;
  }
  message.error(msg);
  return Promise.reject(error);
});

export default http;
